import { ReduxContext } from "./Context";
import { useContext, useEffect, useState, useCallback } from "react";
import { bindActionCreators } from "../kredux/index";
function useUpdate() {
      let [, setUpdateBolean] = useState(false);
      const forceUpdate = useCallback(() => {
            setUpdateBolean(prev => !prev);
      }, []);
      return { forceUpdate };
}

export default function connect(mapStateToProps, mapDispatchToProps) {
      return (WrapperComponent) => {
            // 返回一个高阶组件
            return (props) => {
                  // 处理数据，然后将数据合入组件的props上
                  const store = useContext(ReduxContext);
                  const {subscribe, dispatch, getState} = store;
                  const { forceUpdate } = useUpdate();
                  useEffect(() => {
                        const unSubscribe = subscribe(() => {
                              forceUpdate();
                        });

                        console.log("订阅", unSubscribe)

                        return () => {
                              console.log("取消订阅")
                              unSubscribe();
                        }
                  }, []);

                  let mapDispatchToPropsObj = {dispatch};

                  // 处理一下不同类型的情况
                  if(typeof mapDispatchToProps === "object"){
                        mapDispatchToPropsObj = bindActionCreators(mapDispatchToProps, dispatch);
                  }else if(typeof mapDispatchToProps === "function"){
                        mapDispatchToPropsObj = mapDispatchToProps(dispatch);
                  }

                  let newProps = {
                        ...mapStateToProps(getState()),
                        ...mapDispatchToPropsObj,
                        ...props,
                  };

                  return <WrapperComponent {...newProps}></WrapperComponent>;
            };
      };
}
